﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ISS.Models;

namespace ISS.Controllers
{
    public class HomeController : Controller
    {

        ISSContext dbContext = new ISSContext();

        //
        // GET: /Home/

        public ActionResult Index()
        {
            if (Session["User"] != null)
            {
                return RedirectToAction("Index", "Album");
            }
            else
            {
                return View();
            }
        }

        public ActionResult Login(RegisterUser model)
        {
            var query = from user in dbContext.dbUsers where user.UserName == model.UserName && user.Password == model.Password select user;
            List<Users> currentUsers = query.ToList<Users>();
            if (currentUsers.Count > 0)
            {
                Users u = currentUsers.First<Users>();
                Session["User"] = u;
                return RedirectToAction("Index", "Album");
            }
            else
            {
                return View("Index");
            }
        }

        [HttpPost]
        public ActionResult Register(RegisterUser model)
        {
            if (ModelState.IsValid)
            {
                Users u = new Users();
                u.UserName = model.UserName;
                u.Email = model.Email;
                u.Password = model.Password;
                u.Phone = model.Phone;

                int result = new ISS.UseDAO().Insert(u, dbContext);

                if (result > 0)
                {
                    ViewBag.Successfull = 1;
                    Session["User"] = u;
                    return RedirectToAction("Index", "Album");
                }
                else
                {
                    ViewBag.Successfull = 0;
                    return View("Index");
                }
            }
            else
            {
                return View("Index");
            }
        }

        public ActionResult LogOut()
        {
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }
    }
}
